using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using TST.SharePoint.Shared;
using System.Xml;
using TST.WebParts.Shared.WebControls;

namespace TST.WebParts
{
    public class ContentTypeConfiguration : ConfigurationControl
    {
        protected Panel panelDatasource;
        protected Table tableDatasource;
        protected Label labelContentTypeGroup;
        protected SortDropDownList selectContentTypeGroup;
        protected Label labelContentType;
        protected SortDropDownList selectContentType;
        protected Label labelScope;
        protected RadioButtonList selectScope;
        protected Label labelincludeDescending;
        protected CheckBox cbkIncludeDescending;
        protected Label labelSelectListType;
        protected SortDropDownList selectListType;
        protected Label labelDisplayOption;
        protected Label labelJustSearchOnQuery;
        protected CheckBox cbkJustSearchOnQuery;
        private Exception _exception;

        public event EventHandler SelectedContentTypeChanged;


        private string[] _supportedHiddenTypes = new string[]
        {
            "0x010108", // Wiki Page
            "0x0102", // Event"
            "0x010801", // Workflow Task
            "0x0109", // Workflow History
            "0x0110", // Post
            "0x0111" // Comment
        };

        protected void selectContentTypeGroup_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                SelectedGroup = selectContentTypeGroup.SelectedValue;
                selectContentType.SelectedValue = "-1";
                WriteSelectedContentType();
                Datasource.ReadConfiguration(CurrentConfiguration);
                if (SelectedContentTypeChanged != null)
                {
                    SelectedContentTypeChanged(this, new EventArgs());
                }
            }
            catch (Exception ex)
            {
                _exception = ex;
            }
        }

        private string SelectedGroup
        {
            get { return (string)(ViewState["selectedGroup"] ?? string.Empty); }
            set { ViewState["selectedGroup"] = value; }
        }

        protected void selectContentType_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (Datasource != null && Datasource is DatasourceContentType)
                {
                    string saveName = ((DatasourceContentType)Datasource).ContentTypeName;
                    if (((DatasourceContentType)Datasource).ContentTypeName != selectContentType.SelectedValue)
                    {
                        WriteSelectedContentType();
                        WriteConfiguration();
                        Datasource.ReadConfiguration(CurrentConfiguration);
                        if (SelectedContentTypeChanged != null)
                        {
                            SelectedContentTypeChanged(this, new EventArgs());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _exception = ex;
            }
        }

        private void WriteSelectedContentType()
        {
            // Check if a property is available for the selected content type.
            string s = selectContentType.SelectedValue;
            if (!CurrentConfiguration.CustomProperties.Contains("contenttype"))
                CurrentConfiguration.CustomProperties.Add(new CustomProperty("contenttype", selectContentType.SelectedValue));
            else
                CurrentConfiguration.CustomProperties["contenttype"].Value = selectContentType.SelectedValue;

        }

        public void WriteConfiguration()
        {
            try
            {
                if (CurrentConfiguration == null)
                {
                    return;
                }

                // Check if a property is available for include descending.
                if (!CurrentConfiguration.CustomProperties.Contains("includedescending"))
                    CurrentConfiguration.CustomProperties.Add(new CustomProperty("includedescending", cbkIncludeDescending.Checked ? "true" : "false"));
                else
                    CurrentConfiguration.CustomProperties["includedescending"].Value = cbkIncludeDescending.Checked ? "true" : "false";

                if (!string.IsNullOrEmpty(selectScope.SelectedValue))
                {
                    // Get the scope and check if a property is available for the scope.
                    if (!CurrentConfiguration.CustomProperties.Contains("scope"))
                        CurrentConfiguration.CustomProperties.Add(new CustomProperty("scope", selectScope.SelectedValue));
                    else
                        CurrentConfiguration.CustomProperties["scope"].Value = selectScope.SelectedValue;
                }

                if (!CurrentConfiguration.CustomProperties.Contains("listservertemplate"))
                    CurrentConfiguration.CustomProperties.Add(new CustomProperty("listservertemplate", selectListType.SelectedValue));
                else
                    CurrentConfiguration.CustomProperties["listservertemplate"].Value = selectListType.SelectedValue;

                CurrentConfiguration.JustSearchOnQuery = cbkJustSearchOnQuery.Checked;
            }
            catch (Exception ex)
            {
                _exception = ex;
            }
        }


        private bool HiddenTypeSupported(SPContentType ct)
        {
            for (int i = 0; i < _supportedHiddenTypes.Length; i++)
                if (ct.Id.ToString().ToLower().StartsWith(_supportedHiddenTypes[i].ToLower()))
                    return true;
            return false;
        }


        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            if (Web == null)
                return;

            try
            {
                string selectedContentType = selectContentType.SelectedValue;
                if ((string.IsNullOrEmpty(selectedContentType) || selectedContentType == "-1") && CurrentConfiguration.CustomProperties.Contains("contenttype"))
                    selectedContentType = CurrentConfiguration.CustomProperties["contenttype"].Value;
                if (string.IsNullOrEmpty(SelectedGroup) && !string.IsNullOrEmpty(selectedContentType) && selectedContentType != "-1")
                {
                    foreach (SPContentType contentType in Web.AvailableContentTypes)
                    {
                        if (string.Compare(contentType.Name, selectedContentType, true) == 0)
                        {
                            SelectedGroup = contentType.Group;
                            break;
                        }
                    }
                }

                selectContentType.Items.Clear();
                selectContentType.Items.Add(new ListItem("-- Select a content type --", "-1"));
                selectContentTypeGroup.Items.Clear();
                selectContentTypeGroup.Items.Add(new ListItem("-- Select a group --", "-1"));

                for (int i = 0; i < Web.AvailableContentTypes.Count; i++)
                {
                    SPContentType ct = Web.AvailableContentTypes[i];
                    if ((!ct.Hidden && ct.Group != "_Hidden") || HiddenTypeSupported(ct))
                    {
                        ListItem group = new ListItem(ct.Group);
                        if (!selectContentTypeGroup.Items.Contains(group))
                            selectContentTypeGroup.Items.Add(group);

                        if (SelectedGroup == ct.Group)
                        {
                            ListItem newCT = new ListItem(ct.Name, ct.Name);
                            selectContentType.Items.Add(newCT);
                            newCT.Selected = (string.Compare(selectedContentType, newCT.Value, true) == 0);
                        }
                    }
                }

                if (!string.IsNullOrEmpty(SelectedGroup))
                    selectContentTypeGroup.SelectedValue = SelectedGroup;

                // Populate dropdownlist with list types.
                string valueListType = selectListType.SelectedValue;
                selectListType.Items.Clear();
                selectListType.Items.Add(new ListItem("-- Select a list template --", "-1"));
                using (SPWeb root = Web.Site.RootWeb)
                {
                    SPListTemplateCollection templates = root.ListTemplates;
                    foreach (SPListTemplate template in templates)
                    {
                        string templateID = template.Name;
                        System.Xml.XmlDocument schema = new XmlDocument();
                        schema.LoadXml(template.SchemaXml);
                        XmlAttribute typeAttribute = schema.DocumentElement.Attributes["Type"];
                        if (typeAttribute != null)
                            templateID = typeAttribute.InnerXml;
                        selectListType.Items.Add(new ListItem(template.Name, templateID));
                    }
                }
                selectListType.SelectedValue = valueListType;
                if (!Page.IsPostBack)
                {
                    ReadConfiguration();
                }
            }
            catch (Exception ex)
            {
                _exception = ex;
            }
        }

        public void ReadConfiguration()
        {
            try
            {
                if (CurrentConfiguration == null)
                {
                    return;
                }
                if (CurrentConfiguration.CustomProperties.Contains("contenttype"))
                {
                    selectContentType.SelectedValue = CurrentConfiguration.CustomProperties["contenttype"].Value;
                }
                cbkIncludeDescending.Checked = (CurrentConfiguration.CustomProperties.Contains("includedescending") && CurrentConfiguration.CustomProperties["includedescending"].Value.ToLower() == "true");
                if (CurrentConfiguration.CustomProperties.Contains("scope"))
                    selectScope.SelectedValue = CurrentConfiguration.CustomProperties["scope"].Value;

                if (CurrentConfiguration.CustomProperties.Contains("listservertemplate"))
                    selectListType.SelectedValue = CurrentConfiguration.CustomProperties["listservertemplate"].Value;

                cbkJustSearchOnQuery.Checked = CurrentConfiguration.JustSearchOnQuery;
            }
            catch (Exception ex)
            {
                _exception = ex;
            }
        }

        protected override void Render(HtmlTextWriter writer)
        {
            try
            {
                base.Render(writer);
            }
            catch (Exception ex)
            {
                _exception = ex;
            }
            if (_exception != null)
            {
                writer.WriteLine(string.Format("Error: {0} - {1}.", _exception.Message, _exception.StackTrace));
                if (_exception.InnerException != null)
                {
                    writer.WriteLine(string.Format("Error: {0} - {1}.", _exception.InnerException.Message, _exception.InnerException.StackTrace));
                }
            }
        }
    }
}
